import { useEffect, useState } from 'react';
import { Card, Row, Col, Statistic, Spin, Typography, Progress } from 'antd';
import { 
  FileTextOutlined, 
  CheckCircleOutlined, 
  ClockCircleOutlined, 
  LineChartOutlined,
  MedicineBoxOutlined,
  SafetyOutlined,
  ExperimentOutlined,
  HeartOutlined,
} from '@ant-design/icons';
import { getRecordStatistics, getAssessmentStatistics } from '@/api';
import type { RecordStatistics, AssessmentStatistics } from '@/api';

const { Title } = Typography;

const Dashboard = () => {
  const [loading, setLoading] = useState(true);
  const [recordStats, setRecordStats] = useState<RecordStatistics | null>(null);
  const [assessmentStats, setAssessmentStats] = useState<AssessmentStatistics | null>(null);

  useEffect(() => {
    loadStatistics();
  }, []);

  const loadStatistics = async () => {
    try {
      setLoading(true);
      const [recordRes, assessmentRes] = await Promise.all([
        getRecordStatistics(),
        getAssessmentStatistics(),
      ]);
      setRecordStats(recordRes.data.data);
      setAssessmentStats(assessmentRes.data.data);
    } catch (error) {
      console.error('加载统计数据失败:', error);
    } finally {
      setLoading(false);
    }
  };

  if (loading) {
    return (
      <div style={{ textAlign: 'center', padding: '100px 0' }}>
        <div className="medical-loading" style={{ 
          display: 'inline-block', 
          padding: '40px 80px', 
          borderRadius: '16px',
          marginBottom: '20px',
        }}>
          <Spin 
            size="large" 
            tip={<span style={{ color: '#52c41a', fontSize: '16px', fontWeight: 500 }}>加载数据中...</span>} 
            indicator={<MedicineBoxOutlined spin style={{ fontSize: 48, color: '#52c41a' }} />}
          />
        </div>
      </div>
    );
  }

  return (
    <div style={{ animation: 'fadeIn 0.6s ease-out' }}>
      <div style={{ marginBottom: 48 }}>
        <h1 className="page-title">数据概览</h1>
        <p className="page-subtitle">DASHBOARD OVERVIEW</p>
      </div>
      
      {/* 创新的统计卡片布局 - 圆形卡片 */}
      <Row gutter={[32, 32]}>
        <Col xs={24} sm={12} lg={6}>
          <div className="stat-card-circle">
            <div style={{ textAlign: 'center' }}>
              <div style={{
                width: 80,
                height: 80,
                borderRadius: '50%',
                background: 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)',
                display: 'flex',
                alignItems: 'center',
                justifyContent: 'center',
                margin: '0 auto 20px',
                boxShadow: '0 8px 20px rgba(102, 126, 234, 0.3)',
              }}>
                <FileTextOutlined style={{ fontSize: 32, color: '#fff' }} />
              </div>
              <div style={{ fontSize: 14, color: '#8F9BB3', marginBottom: 8, fontWeight: 500, letterSpacing: '0.5px' }}>
                病历总数
              </div>
              <div style={{ fontSize: 40, fontWeight: 300, color: '#2E3A59', marginBottom: 12 }}>
                {recordStats?.total_records || 0}
              </div>
              <Progress 
                percent={100} 
                strokeColor={{
                  '0%': '#667eea',
                  '100%': '#764ba2',
                }}
                showInfo={false} 
                strokeWidth={6}
                style={{ marginTop: '8px' }}
              />
            </div>
          </div>
        </Col>
        <Col xs={24} sm={12} lg={6}>
          <div className="stat-card-circle">
            <div style={{ textAlign: 'center' }}>
              <div style={{
                width: 80,
                height: 80,
                borderRadius: '50%',
                background: 'linear-gradient(135deg, #50E3C2 0%, #00D4AA 100%)',
                display: 'flex',
                alignItems: 'center',
                justifyContent: 'center',
                margin: '0 auto 20px',
                boxShadow: '0 8px 20px rgba(80, 227, 194, 0.3)',
              }}>
                <CheckCircleOutlined style={{ fontSize: 32, color: '#fff' }} />
              </div>
              <div style={{ fontSize: 14, color: '#8F9BB3', marginBottom: 8, fontWeight: 500, letterSpacing: '0.5px' }}>
                已评估
              </div>
              <div style={{ fontSize: 40, fontWeight: 300, color: '#2E3A59', marginBottom: 12 }}>
                {recordStats?.assessed_records || 0}
              </div>
              <Progress 
                percent={recordStats?.total_records ? Math.round((recordStats.assessed_records / recordStats.total_records) * 100) : 0}
                strokeColor={{
                  '0%': '#50E3C2',
                  '100%': '#00D4AA',
                }}
                showInfo={true}
                strokeWidth={6}
                style={{ marginTop: '8px' }}
              />
            </div>
          </div>
        </Col>
        <Col xs={24} sm={12} lg={6}>
          <div className="stat-card-circle">
            <div style={{ textAlign: 'center' }}>
              <div style={{
                width: 80,
                height: 80,
                borderRadius: '50%',
                background: 'linear-gradient(135deg, #FFAA00 0%, #FF6B9D 100%)',
                display: 'flex',
                alignItems: 'center',
                justifyContent: 'center',
                margin: '0 auto 20px',
                boxShadow: '0 8px 20px rgba(255, 107, 157, 0.3)',
              }}>
                <ClockCircleOutlined style={{ fontSize: 32, color: '#fff' }} />
              </div>
              <div style={{ fontSize: 14, color: '#8F9BB3', marginBottom: 8, fontWeight: 500, letterSpacing: '0.5px' }}>
                待评估
              </div>
              <div style={{ fontSize: 40, fontWeight: 300, color: '#2E3A59', marginBottom: 12 }}>
                {recordStats?.pending_records || 0}
              </div>
              <Progress 
                percent={recordStats?.total_records ? Math.round((recordStats.pending_records / recordStats.total_records) * 100) : 0}
                strokeColor={{
                  '0%': '#FFAA00',
                  '100%': '#FF6B9D',
                }}
                showInfo={true}
                strokeWidth={6}
                style={{ marginTop: '8px' }}
              />
            </div>
          </div>
        </Col>
        <Col xs={24} sm={12} lg={6}>
          <div className="stat-card-circle">
            <div style={{ textAlign: 'center' }}>
              <div style={{
                width: 80,
                height: 80,
                borderRadius: '50%',
                background: 'linear-gradient(135deg, #4A90E2 0%, #0095FF 100%)',
                display: 'flex',
                alignItems: 'center',
                justifyContent: 'center',
                margin: '0 auto 20px',
                boxShadow: '0 8px 20px rgba(0, 149, 255, 0.3)',
              }}>
                <LineChartOutlined style={{ fontSize: 32, color: '#fff' }} />
              </div>
              <div style={{ fontSize: 14, color: '#8F9BB3', marginBottom: 8, fontWeight: 500, letterSpacing: '0.5px' }}>
                平均分数
              </div>
              <div style={{ fontSize: 40, fontWeight: 300, color: '#2E3A59', marginBottom: 12 }}>
                {(assessmentStats?.average_score || 0).toFixed(1)}
              </div>
              <Progress 
                percent={assessmentStats?.average_score || 0}
                strokeColor={{
                  '0%': '#4A90E2',
                  '100%': '#0095FF',
                }}
                showInfo={false}
                strokeWidth={6}
                style={{ marginTop: '8px' }}
              />
            </div>
          </div>
        </Col>
      </Row>

      {assessmentStats && assessmentStats.common_issues.length > 0 && (
        <div style={{ marginTop: 48 }}>
          <div style={{ marginBottom: 24 }}>
            <h2 style={{ 
              fontSize: '24px', 
              fontWeight: 300,
              color: '#2E3A59',
              marginBottom: 8,
              letterSpacing: '-0.5px',
            }}>
              常见问题统计
            </h2>
            <p className="page-subtitle">COMMON ISSUES ANALYSIS</p>
          </div>
          <Row gutter={[24, 24]}>
            {assessmentStats.common_issues.map((issue, index) => {
              const colors = [
                { from: '#667eea', to: '#764ba2' },
                { from: '#50E3C2', to: '#00D4AA' },
                { from: '#FFAA00', to: '#FF6B9D' },
                { from: '#4A90E2', to: '#0095FF' },
              ];
              const color = colors[index % colors.length];
              return (
                <Col xs={24} sm={12} md={6} key={index}>
                  <div className="medical-card" style={{
                    padding: 32,
                    textAlign: 'center',
                    position: 'relative',
                  }}>
                    <div style={{
                      width: 60,
                      height: 60,
                      borderRadius: '50%',
                      background: `linear-gradient(135deg, ${color.from} 0%, ${color.to} 100%)`,
                      display: 'flex',
                      alignItems: 'center',
                      justifyContent: 'center',
                      margin: '0 auto 16px',
                      boxShadow: `0 6px 16px ${color.from}40`,
                    }}>
                      <SafetyOutlined style={{ fontSize: 24, color: '#fff' }} />
                    </div>
                    <div style={{ fontSize: 13, color: '#8F9BB3', marginBottom: 8, fontWeight: 500 }}>
                      {getIssueTypeName(issue.type)}
                    </div>
                    <div style={{ fontSize: 32, fontWeight: 300, color: '#2E3A59' }}>
                      {issue.count}
                    </div>
                  </div>
                </Col>
              );
            })}
          </Row>
        </div>
      )}

      {assessmentStats && (
        <div style={{ marginTop: 48 }}>
          <div style={{ marginBottom: 24 }}>
            <h2 style={{ 
              fontSize: '24px', 
              fontWeight: 300,
              color: '#2E3A59',
              marginBottom: 8,
              letterSpacing: '-0.5px',
            }}>
              质量分数分布
            </h2>
            <p className="page-subtitle">SCORE DISTRIBUTION</p>
          </div>
          <div className="medical-card" style={{ padding: 40 }}>
            <Row gutter={[32, 32]}>
              {Object.entries(assessmentStats.score_distribution).map(([range, count], index) => {
                const percentage = (count / recordStats?.total_records || 0) * 100;
                return (
                  <Col xs={24} sm={12} md={6} key={range}>
                    <div style={{ textAlign: 'center' }}>
                      <div style={{
                        fontSize: 14,
                        color: '#8F9BB3',
                        marginBottom: 16,
                        fontWeight: 500,
                        letterSpacing: '0.5px',
                      }}>
                        {range}分段
                      </div>
                      <div style={{
                        position: 'relative',
                        width: 120,
                        height: 120,
                        margin: '0 auto 16px',
                      }}>
                        <Progress
                          type="circle"
                          percent={percentage}
                          size={120}
                          strokeWidth={8}
                          strokeColor={{
                            '0%': '#667eea',
                            '100%': '#764ba2',
                          }}
                          format={() => (
                            <div>
                              <div style={{ fontSize: 28, fontWeight: 300, color: '#2E3A59' }}>
                                {count}
                              </div>
                              <div style={{ fontSize: 12, color: '#8F9BB3' }}>
                                份
                              </div>
                            </div>
                          )}
                        />
                      </div>
                      <div style={{ fontSize: 12, color: '#8F9BB3' }}>
                        占比 {percentage.toFixed(1)}%
                      </div>
                    </div>
                  </Col>
                );
              })}
            </Row>
          </div>
        </div>
      )}
    </div>
  );
};

const getIssueTypeName = (type: string): string => {
  const typeMap: Record<string, string> = {
    completeness: '完整性问题',
    standardization: '规范性问题',
    consistency: '一致性问题',
    accuracy: '准确性问题',
  };
  return typeMap[type] || type;
};

export default Dashboard;

